/**
 * eFashion Tracking SDK
 * author: jabez.huang
 * version: v1.1
 */

import {
  MERCHANT_INFO,
  CUSTOMER_INFO
} from '@/utils/constant';
import api from '@/api/api.js';
// import matomo from 'wechat-matomo';
const GATEWAYIDJSON = {
  formal: 'efc-sg-prod-9g2vqh1q007068d1',
  trial: 'efc-sg-test-tke-8gsfog1ydae06fe0'
}
class EFSTracking {
  matomoReportUrl = 'https://analysis.cloud.efashionchina.com/matomo.php';
  matomoSiteId = '5';
  currentUrl = '';
  matomoPageUrl = '';
  campagin = '';
  isTrackPage = 0;
  onshow_time = 0; //页面onShow时的时间戳
  event_duration = 0; //页面停留时长
  platformConfig = {
    wx: {
      name: "Weixin",
      path: "./weixin"
    }
  };
  Config = Object.assign({}, this.platformConfig.wx, {
    platform: "MinP",
    scnPrefix: "",
    appHandlers: ["onShow", "onHide", "onError"],
    pageHandlers: ["onLoad", "onShow", "onShareAppMessage", "onShareTimeline", "onTabItemTap", "onHide",
      "onUnload"],
    actionEventTypes: ["onclick", "tap", "longpress", "blur", "change", "submit", "confirm", "getuserinfo",
      "getphonenumber", "contact"
    ],
    originalApp: App,
    originalPage: Page,
    originalComponent: Component,
    originalBehavior: Behavior,
    canHook: !0,
    hooks: {
      App: !0,
      Page: !0,
      Component: !0,
      Behavior: !0
    },
    lisiteners: {
      app: {
        appShow: "onShow",
        appClose: "onHide",
        appError: "onError"
      },
      page: {
        pageLoad: "onLoad",
        pageShow: "onShow",
        pageHide: "onHide",
        pageClose: "onUnload",
        tabTap: "onTabItemTap",
        shareApp: "onShareAppMessage",
        shareTime: "onShareTimeline"
      },
      actions: {
        click: ["onclick", "tap", "longpress", "getuserinfo", "getphonenumber", "contact"],
        change: ["blur", "change", "confirm"],
        submit: ["submit"]
      }
    }
  });

  constructor() {
    if (EFSTracking.prototype.Instance === undefined) {
      EFSTracking.prototype.Instance = this
    }
    return EFSTracking.prototype.Instance
  }

  setCampagin(campagin) {
    // console.log( 'campagin:', campagin )
    uni.setStorageSync("efs_campagin", campagin);
    this.campagin = campagin;
  }

  /**
   * 跟踪页面
   * @param {String} eventType 事件名称。onShow/onHide/onUnload ...
   * @param {Object} params
   * @param {Number} eventDuration 页面停留时长，秒
   */
  async trackingPage(eventType, params, eventDuration) {
    let pages = params;
    this.currentUrl = pages.$page && pages.$page.fullPage ? pages.$page.fullPath : pages.route;
    let titles = getApp().globalData.title;
    getApp().globalData.pageUrl = this.currentUrl; //TODO 有什么用处？
    let data = {
      "eventType": eventType,
      "campaign": uni.getStorageSync("efs_campagin") ? uni.getStorageSync("efs_campagin") : "",
      "customerId": 0,
      // "data": pages.data,
      "ip": uni.getStorageSync("efs_tracking_ip"),
      "merchantId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
      "model": uni.getStorageSync('efs_tracking_model').model ? uni.getStorageSync('efs_tracking_model').model :
        "***",
      "path": this.currentUrl,
      "duration": eventDuration,
      "scene": uni.getStorageSync("efs_tracking_scene"),
      "size": uni.getStorageSync('efs_tracking_model').screenWidth + "*" + uni.getStorageSync('efs_tracking_model')
        .screenHeight,
      "storeId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
      "title": titles[this.currentUrl] || "其他页面",
      "uniqueId": uni.getStorageSync("efs_tracking_unionId"),
      "experimentId": uni.getStorageSync("abId"),
      "versionName": uni.getStorageSync("abVersion"),
    }
    // debugger;
    // if (eventDuration)
    //   data.put("duration", eventDuration); // 页面停留时长 s
    if (api.environment == 'formal') {
      let res = await wx.cloud.callContainer({
        path: "/cloud-tracking-service/customer/tracking/page",
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt,
          'Content-Type': 'application/json',
          'Content-Type': 'application/json',
          'X-WX-EXCLUDE-CREDENTIALS': 'unionid, cloudbase-access-token, openid',
          'X-WX-GATEWAY-ID': GATEWAYIDJSON[api.environment],
          'HOST': api.baseUrl.substring(8)
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking page', res.data);
          }
        }
      });
    } else {
      let res = await uni.request({
        url: api.baseUrl + "/cloud-tracking-service/customer/tracking/page",
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt,
          'Content-Type': 'application/json'
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking page', res.data);
          }
        }
      });

    }

  }

  /**
   * 跟踪事件行为
   * @param {Object} eventType 事件类型
   * @param {Object} value 事件值
   * @param {Object} params
   */
  async trackingAction(eventType, value, params) {
    //return false;
    let data = {
      "campaign": uni.getStorageSync("efs_campagin") ? uni.getStorageSync("efs_campagin") : "",
      "customerId": 0,
      "data": params == '' ? {} : params,
      "ip": uni.getStorageSync("efs_tracking_ip"),
      "merchantId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
      "path": this.currentUrl,
      "scene": uni.getStorageSync("efs_tracking_scene"),
      "storeId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
      "uniqueId": uni.getStorageSync("efs_tracking_unionId"),
      "value": value,
      "experimentId": uni.getStorageSync("abId"),
      "versionName": uni.getStorageSync("abVersion"),
    }
    if (api.environment == 'formal') {
      let res = await wx.cloud.callContainer({
        path: "/cloud-tracking-service/customer/tracking/action?eventType=" + eventType,
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt,
          'X-WX-EXCLUDE-CREDENTIALS': 'unionid, cloudbase-access-token, openid',
          'X-WX-GATEWAY-ID': GATEWAYIDJSON[api.environment],
          'HOST': api.baseUrl.substring(8)
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking action', res.data);
          }
        }
      });
    } else {
      let res = await uni.request({
        url: api.baseUrl + "/cloud-tracking-service/customer/tracking/action?eventType=" + eventType,
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking action', res.data);
          }
        }
      });

    }

  }

  /**
   * 跟踪加购行为
   * @param {Object} itemId
   * @param {Object} itemName
   * @param {Object} itemPrice
   * @param {Object} valueCode
   * @param {Object} valueName
   * @param {Object} skuCode
   * @param {Object} params
   */
  async trackingCart(itemId, itemName, itemPrice, valueCode, valueName, skuCode, imageSrc, params) {
    //return false;
    let data = {
      "path": this.currentUrl,
      "campaign": uni.getStorageSync("efs_campagin") ? uni.getStorageSync("efs_campagin") : "",
      "customerId": 0,
      "data": params == '' ? {} : params,
      "itemId": itemId,
      "itemName": itemName,
      "itemPrice": parseInt(itemPrice * 100),
      "valueCode": parseInt(valueCode),
      "valueName": valueName,
      "skuCode": skuCode,
      "merchantId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
      "scene": uni.getStorageSync("efs_tracking_scene"),
      "storeId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
      "uniqueId": uni.getStorageSync("efs_tracking_unionId"),
      "imageSrc": imageSrc,
      "experimentId": uni.getStorageSync("abId"),
      "versionName": uni.getStorageSync("abVersion"),
    }
    if (api.environment == 'formal') {
      let res = await wx.cloud.callContainer({
        path: "/cloud-tracking-service/customer/tracking/cart",
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt,
          'X-WX-EXCLUDE-CREDENTIALS': 'unionid, cloudbase-access-token, openid',
          'X-WX-GATEWAY-ID': GATEWAYIDJSON[api.environment],
          'HOST': api.baseUrl.substring(8)
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking cart', res.data);
          }
        }
      });
    } else {
      let res = await uni.request({
        url: api.baseUrl + "/cloud-tracking-service/customer/tracking/cart",
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking cart', res.data);
          }
        }
      });

    }

  }

  /**
   * 跟踪订单支付
   * @param {Object} orderStatus
   * @param {Object} orderId
   * @param {Object} orderItems
   * @param {Object} orderAmount
   * @param {Object} orderShippingFee
   * @param {Object} orderDiscountAmount
   * @param {Object} orderSubtotal
   */
  async trackingOrder(orderStatus, orderId, orderItems, orderAmount, orderShippingFee, orderDiscountAmount,
    orderSubtotal) {
    //return false;
    let items = [];
    let i = 0;
    for (let index in orderItems) {
      let amount = orderItems[index].amount;
      if (amount == undefined) {
        amount = parseFloat(orderItems[index].price * orderItems[index].qty)
      }
      let item = {
        'itemId': orderItems[index].itemId,
        'itemName': orderItems[index].itemName,
        'categoryId': 100,
        'categoryName': 'default',
        'orderQty': orderItems[index].qty,
        'rowTotal': parseInt(amount * 100),
        'unitPrice': parseInt(orderItems[index].price * 100),
        'discountAmount': parseInt(orderItems[index].discountFee * 100)
      };
      items.push(item);
    }
    let data = {
      "path": this.currentUrl,
      "campaign": uni.getStorageSync("efs_campagin") ? uni.getStorageSync("efs_campagin") : "",
      "customerId": 0,
      "data": {},
      "ip": uni.getStorageSync("efs_tracking_ip"),
      "merchantId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
      "scene": uni.getStorageSync("efs_tracking_scene"),
      "storeId": uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
      "uniqueId": uni.getStorageSync("efs_tracking_unionId"),
      "orderAmount": parseInt(orderAmount * 100),
      "orderDiscountAmount": parseInt(orderDiscountAmount * 100),
      "orderId": orderId,
      "orderShippingFee": parseInt(orderShippingFee * 100),
      "orderSubtotal": parseInt(orderSubtotal * 100),
      "orderItems": items,
      "experimentId": uni.getStorageSync("abId"),
      "versionName": uni.getStorageSync("abVersion"),
    }
    if (api.environment == 'formal') {
      let res = await wx.cloud.callContainer({
        path: "/cloud-tracking-service/customer/tracking/order?orderStatus=" + orderStatus,
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt,
          'X-WX-EXCLUDE-CREDENTIALS': 'unionid, cloudbase-access-token, openid',
          'X-WX-GATEWAY-ID': GATEWAYIDJSON[api.environment],
          'HOST': api.baseUrl.substring(8)
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking order', res.data);
          }
        }
      });
    } else {
      let res = await uni.request({
        url: api.baseUrl + "/cloud-tracking-service/customer/tracking/order?orderStatus=" + orderStatus,
        method: 'POST',
        data: data,
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt
        },
        success: res => {
          if (res.data.code == 200) {
            // console.log('tracking order', res.data);
          }
        }
      });

    }

  }

  /**
   * 获取unionId
   */
  async getUnionId() {
    let UUID = "";
    uni.setStorageSync('efs_tracking_unionId', this.uuid());
  }

  /**
   * 获取IP
   */
  async getIp() {
    //return false;
    if (api.environment == 'formal') {
      let res = await wx.cloud.callContainer({
        path: '/client-ip-service',
        method: 'GET',
        data: {},
        timeout: 10000,
        header: {
          'Content-Type': 'application/json',
          'X-WX-EXCLUDE-CREDENTIALS': 'unionid, cloudbase-access-token, openid',
          'X-WX-GATEWAY-ID': GATEWAYIDJSON[api.environment],
          'HOST': api.baseUrl.substring(8)
        },
        success: res => {
          if (res.data.code == 1000) {
            uni.setStorageSync("efs_tracking_ip", res.data.data);
          } else {
            uni.setStorageSync("efs_tracking_ip", "0.0.0.0");
          }

          uni.getSystemInfo({
            success(res) {
              uni.setStorageSync('efs_tracking_model', res);
            }
          });
        }
      });
    } else {
      let res = await uni.request({
        url: api.baseUrl + '/client-ip-service',
        method: 'GET',
        data: {},
        timeout: 10000,
        header: {
          'Content-Type': 'application/json'
        },
        success: res => {
          if (res.data.code == 1000) {
            uni.setStorageSync("efs_tracking_ip", res.data.data);
          } else {
            uni.setStorageSync("efs_tracking_ip", "0.0.0.0");
          }

          uni.getSystemInfo({
            success(res) {
              uni.setStorageSync('efs_tracking_model', res);
            }
          });
        }
      });

    }

  }

  /**
   * 初始化IP和UnionId
   * @param {Object} data
   */
  initTracker(data) {
    uni.setStorageSync('efs_tracking_scene', data.scene);
    this.proxyVue(data.vue, this);
    //重新Init 即移除Campaign
    uni.removeStorageSync('efs_campagin');

    if (!uni.getStorageSync('efs_tracking_ip')) {
      this.getIp();
    }

    if (!uni.getStorageSync('efs_tracking_unionId')) {
      this.getUnionId();
    }
  }

  /**
   * matomo发送tracking
   * @param {Object} params
   */
  matomoTrackingPage(params) {
    let titles = getApp().globalData.title;
    let enableMatomo = uni.getStorageSync('enableMatomo')
    this.matomoPageUrl = this.currentUrl;
    getApp().globalData.initTrack = 1;
    // matomo.initTracker(this.matomoReportUrl, this.matomoSiteId, {
    //   titles
    // })

    let title = titles[this.matomoPageUrl];
    if (titles.hasOwnProperty(this.matomoPageUrl)) {
      title = titles[this.matomoPageUrl]
    }
    // matomo.tracker.trackPageView(title || '其他页面', this.matomoPageUrl);
  }

  /**
   * 代理Vue底层，监听created和beforeMount
   * @param {Object} t
   * @param {Object} e
   */
  proxyVue(t, e) {
    void 0 !== t.mixin && t.mixin({
      created: function() {
        if (!this.$options.methods) return;
        const t = Object.keys(this.$options.methods);
        for (let e of Object.keys(this)) 0 > t.indexOf(e) || "function" != typeof this[e] || (Object
          .defineProperty(this[
            e], "proxiedName", {
            value: e
          }), Object.defineProperty(this[e], "isProxied", {
            value: !0
          }))
      },
      beforeMount: function() {
        let t = this.$root;
        t.$mp && "page" === t.$mp.mpType ? t.$mp.page && (e.vueRootVMs[t.$mp.page.route] = t) : "page" === t
          .mpType &&
          "page" === this.mpType && t.$mp.page &&
          this.$EFSTracking.instrumentPageComponent(t.$mp.page)
      }
    })
  }

  /**
   * 监听Config配置方法，做出onShow监听
   * @param {Object} t
   */
  instrumentPageComponent(t) {
    if (t) return this.Config.pageHandlers.map(function(e) {
      if ("function" == typeof t[e]) {
        const i = t[e];
        t[e] = function() {
          let t = i.apply(this, arguments),
            n = Array.prototype.slice.call(arguments);
          return t && n.push(t), (function(t, e, i) {
            try {
              if (e === 'onLoad') {
                // console.info("proxy onLoad occured........" + e);
                //获取和应用页面实验版本数据
                t.$vm.$EFSABTestTracking.tryApplyAbConfigForPage(t);
              } else if (e === 'onShow') {
                efs.event_duration = 0;
                efs.onshow_time = (new Date()).getTime();
                // console.info("proxy onShow occured........" + e)
                efs.trackingPage(e, t);
                efs.matomoTrackingPage(t);
              } else if (e === 'onHide' || e === 'onUnload') {
                //                  console.info("proxy event occured........" + e + ",开始计算d")
                var current_time = (new Date()).getTime();
                if (efs.onshow_time && (current_time - efs.onshow_time > 0) &&
                  ((current_time - efs.onshow_time) / 3600000 < 24)) {
                  efs.event_duration = (current_time - efs.onshow_time) / 1000;
                }
                // efs.onshow_time = 0;
                //                   console.info("proxy event occured........#" + e + ", d:" + efs.event_duration)
                efs.trackingPage(e, t, efs.event_duration);
              }
            } catch (err) {
              // console.error("proxy Tracking event fail,e:" + e + "," + err)
            }

          })(this, e, n), t
        }
      }
    }), t
  }

  /**
   * 生成UUId
   */
  uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "";

    var uuid = s.join("");
    return uuid;
  }
}

const efs = new EFSTracking();
export default efs